//
//  HTTPManager.swift
//  DYSwiftFramework
//
//  Created by 黄德玉 on 2018/8/6.
//  Copyright © 2018年 none. All rights reserved.
//

import Alamofire

let cacheDic = "com.hdy.test"

class HTTPManager {
    private var sessionManager:SessionManager?;
    public static let `default`:HTTPManager = {
        let manager = HTTPManager();
        return manager;
    }();
    init() {
        sessionManager = createASession()           // 为manager创建一个共享的session实例
    }
    
    private func createASession()->SessionManager{
        let configuration = URLSessionConfiguration.default
        //配置acceptEncoding，Accept-Language，User-Agent
        configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
        configuration.timeoutIntervalForRequest = 15;
        configuration.allowsCellularAccess = true;
        configuration.urlCache = URLCache(memoryCapacity: 1024 * 1024, diskCapacity: 1024 * 1024, diskPath: cacheDic); //如果不指定urlCache 则使用默认的共享urlCache
        configuration.requestCachePolicy = .useProtocolCachePolicy;         // 先取默认的缓存方式。缓存策略需要针对请求来做缓存
        let aSession = SessionManager(configuration: configuration)
        aSession.adapter = nil;  // 每个request创建的时候的adapter(TODO: 未实现)
        aSession.retrier = nil;  // 重试机制 (TODO: 未实现)
        return aSession;
    }
    
    public func request(_ request:HTTPRequest,_ callback:@escaping (HTTPError?,Any?)->Void)->Void{
        do{
            let url = request.baseURL
            var urlRequest = try URLRequest(url: url!, method: request.method)
            
            if let timeout = request.timeout {
                urlRequest.timeoutInterval = timeout
            }
            if let cachePolicy = request.cachePolicy {
                urlRequest.cachePolicy = cachePolicy
            }
            if let requestHeader = request.requestHeader {
                urlRequest.allHTTPHeaderFields = requestHeader
            }
            
            var aSession = sessionManager;
            if let needASession = request.needIndependentSession {
                if needASession{
                    aSession = self.createASession();
                }
            }

            aSession!
                .request(urlRequest)
                .validate(statusCode: 200..<300)
                .validate(contentType: ["application/json","text/plain"])
                .responseJSON { [weak aSession] (response) in
                    if let needASession = request.needIndependentSession {
                        if needASession{
                            aSession!.session.finishTasksAndInvalidate();
                        }
                    }
                    switch response.result {
                    case .success(let value):
                        debugPrint("Validate success value is \(value)");
                        //这个是用来检查约定数据格式是否有误
                        if let responseCheckBlock = request.responseCheckBlock {
                            let checkResult = responseCheckBlock(nil,response)
                            if !checkResult.0 { //如果没有验证通过
                                callback(checkResult.1,nil)
                            }
                        }
                        if let responseDecodeBlock = request.reponseDecodeBlock {
                            let decodeResult = responseDecodeBlock(response)
                            callback(nil,decodeResult);
                        }
                    case .failure(let error):
                        debugPrint(error)
                        let afError:AFError = error as! AFError
                        //这个直接检查AFError
                        if let responseCheckBlock = request.responseCheckBlock{
                            let checkResult = responseCheckBlock(afError,nil)
                            if !checkResult.0 { //如果没有验证通过
                                callback(checkResult.1,nil)
                            }
                        }
                    }
            }
        }catch(let error){
            let afError:AFError = error as! AFError
            if let responseCheckBlock = request.responseCheckBlock{
                let checkResult = responseCheckBlock(afError,nil)
                if !checkResult.0 { //如果没有验证通过
                    callback(checkResult.1,nil)
                }
            }
        }
    }

}
